#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import threading
import time

def start_scheduler():
    """启动定时任务"""
    try:
        from ai.scripts.scheduled_data_collection import main as scheduler_main
        print("[INFO] 启动定时数据收集服务...")
        scheduler_main()
    except Exception as e:
        print(f"[ERROR] 定时任务启动失败: {e}")

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Didi.settings.dev')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    
    # 检查是否是启动服务器命令
    if len(sys.argv) > 1 and sys.argv[1] == 'runserver':
        # 在后台线程中启动定时任务
        scheduler_thread = threading.Thread(target=start_scheduler, daemon=True)
        scheduler_thread.start()
        print("[SUCCESS] 定时任务已在后台启动")
    
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
